package com.example.controller;

import com.example.entity.BaseResponse;
import com.example.entity.PersonEntity;
import com.example.entity.PersonSearchEntity;
import com.example.entity.ResultBody;
import com.example.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class PersonController {
    @Autowired
    PersonService personService;
    @RequestMapping("/getPerson")
    public PersonEntity getPerson(int id){
        return  new PersonEntity();
    }

    /**
     * 列出所有人员信息
     * @return  人员信息列表的封装对象
     */
    @RequestMapping("/listPerson")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<PersonEntity> listPerson(){
        List<PersonEntity> personList =  personService.findAll();
        return new BaseResponse<PersonEntity>(0, "success", personList.size(), personList);
//        return personService.findAll();
    }

    /**
     *
     * @param method 人员保存方法， 可选值为“添加”或“修改”
     * @param personEntity 人员信息实体类
     * @return 返回操作结果的封装对象
     */
    @RequestMapping("/savePerson")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody savePerson(String method, PersonEntity personEntity){
        System.out.println(personEntity.toString());
        System.out.println(method);
        if(personService.savePerson(method, personEntity)){
            return new ResultBody(1, "success");
        } else{
            return new ResultBody(1, "fail");
        }
    }

    /**
     * 删除人员信息
     * @param id 人员id
     * @return 返回操作结果的封装对象
     */
    @RequestMapping("/deletePerson")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody deletePerson(int id){
        if(personService.deletePerson(id)) {
            return new ResultBody(0, "success");
        } else {
            return new ResultBody(1, "fail");
        }
    }
    @RequestMapping("/personSearch")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<PersonEntity> personSearch(PersonSearchEntity personSearch){
        System.out.println(personSearch);
        personSearch.setStart((personSearch.getPage()-1)*personSearch.getLimit());
        List<PersonEntity> personList = personService.personSearch(personSearch);
        return new BaseResponse<PersonEntity>(0, "success",
                personService.personSearchCount(personSearch), personList);
    }
}
